// 创建XMLHttpRequest对象
const xhr = new XMLHttpRequest();

// 设置请求的URL，这里假设JSON Server运行在本地3000端口，且学生数据接口为 /students
const url = 'http://localhost:3000/students';

// 加载学生数据并渲染表格的函数
function loadStudents() {
  xhr.open('GET', url, true);
  xhr.responseType = 'json';
  xhr.onload = function () {
    if (xhr.status === 200) {
      const students = xhr.response;
      const tableBody = document.getElementById('student-table').getElementsByTagName('tbody')[0];
      tableBody.innerHTML = ''; // 清空原有表格内容
      students.forEach(student => {
        const row = document.createElement('tr');
        const nameCell = document.createElement('td');
        nameCell.textContent = student.name;
        const ageCell = document.createElement('td');
        ageCell.textContent = student.age;
        const majorCell = document.createElement('td');
        majorCell.textContent = student.major;
        const gradeCell = document.createElement('td');
        gradeCell.textContent = student.grade;

        const actionsCell = document.createElement('td');
        const editButton = document.createElement('button');
        editButton.textContent = '修改';
        editButton.addEventListener('click', function () {
          // 填充表单用于修改
          document.getElementById('name').value = student.name;
          document.getElementById('age').value = student.age;
          document.getElementById('major').value = student.major;
          document.getElementById('grade').value = student.grade;
          document.getElementById('saveButton').dataset.id = student.id; // 记录当前要修改的学生id
          document.getElementById('formContainer').style.display = 'block';
        });

        const deleteButton = document.createElement('button');
        deleteButton.textContent = '删除';
        deleteButton.addEventListener('click', function () {
          deleteStudent(student.id);
        });

        actionsCell.appendChild(editButton);
        actionsCell.appendChild(deleteButton);

        row.appendChild(nameCell);
        row.appendChild(ageCell);
        row.appendChild(majorCell);
        row.appendChild(gradeCell);
        row.appendChild(actionsCell);

        tableBody.appendChild(row);
      });
    } else {
      console.error('请求失败，状态码：', xhr.status);
    }
  };
  xhr.onerror = function () {
    console.error('请求发生错误');
  };
  xhr.send();
}

// 新增学生数据的函数
function addStudent(studentData) {
  xhr.open('POST', url, true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onload = function () {
    if (xhr.status === 201) {
      loadStudents(); // 新增成功后重新加载数据渲染表格
      document.getElementById('formContainer').style.display = 'none'; // 隐藏表单
    } else {
      console.error('新增学生失败，状态码：', xhr.status);
    }
  };
  xhr.onerror = function () {
    console.error('新增学生请求发生错误');
  };
  xhr.send(JSON.stringify(studentData));
}

// 修改学生数据的函数
function updateStudent(studentData, studentId) {
  const updateUrl = `${url}/${studentId}`;
  xhr.open('PUT', updateUrl, true);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.onload = function () {
    if (xhr.status === 200) {
      loadStudents(); // 修改成功后重新加载数据渲染表格
      document.getElementById('formContainer').style.display = 'none'; // 隐藏表单
    } else {
      console.error('修改学生失败，状态码：', xhr.status);
    }
  };
  xhr.onerror = function () {
    console.error('修改学生请求发生错误');
  };
  xhr.send(JSON.stringify(studentData));
}

// 删除学生数据的函数
function deleteStudent(studentId) {
  const deleteUrl = `${url}/${studentId}`;
  xhr.open('DELETE', deleteUrl, true);
  xhr.onload = function () {
    if (xhr.status === 200) {
      loadStudents(); // 删除成功后重新加载数据渲染表格
    } else {
      console.error('删除学生失败，状态码：', xhr.status);
    }
  };
  xhr.onerror = function () {
    console.error('删除学生请求发生错误');
  };
  xhr.send();
}

// 页面加载时加载学生数据并渲染表格
window.onload = function () {
  loadStudents();

  // 点击新增按钮显示表单
  document.getElementById('addButton').addEventListener('click', function () {
    document.getElementById('formContainer').style.display = 'block';
    document.getElementById('saveButton').dataset.id = ''; // 清空修改时的id标识
  });

  // 点击保存按钮，根据情况新增或修改学生数据
  document.getElementById('saveButton').addEventListener('click', function () {
    const name = document.getElementById('name').value;
    const age = document.getElementById('age').value;
    const major = document.getElementById('major').value;
    const grade = document.getElementById('grade').value;
    const studentData = { name, age, major, grade };
    const studentId = this.dataset.id;
    if (studentId) {
      updateStudent(studentData, studentId);
    } else {
      addStudent(studentData);
    }
  });

  // 点击取消按钮隐藏表单
  document.getElementById('cancelButton').addEventListener('click', function () {
    document.getElementById('formContainer').style.display = 'none';
  });
};